package com.filyar.htyd.config.interceptor;

import cn.hutool.core.date.DateUtil;
import com.filyar.htyd.common.ExceptionEnum;
import com.filyar.htyd.exception.ServiceException;
import com.filyar.htyd.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author Feiliya
 * @date: 2024/3/23 18:38
 * @email: root@filyar.com
 */
@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {

    private final static String LIMIT_PREFIX = "limit:";
    private final static String BLOCK_PREFIX = "block:";
    @Value("${rateLimiter.limitTime}")
    private int limitTime;
    @Value("${rateLimiter.limitCount}")
    private int limitCount;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = IpUtils.getIpAddress(request);
        //判断接口是否是/compareTask/page,如果是不进行+1操作
        if (!"/compareTask/page".equals(request.getRequestURI())){
            Long count = stringRedisTemplate.opsForValue().increment(LIMIT_PREFIX + ip, 1);
            if (count == 1){
                stringRedisTemplate.expire(LIMIT_PREFIX + ip, limitTime, TimeUnit.HOURS);
            }else if (count > limitCount){
                log.error("{}恶意行为触发，IP:{}", DateUtil.now(),ip);
                stringRedisTemplate.opsForValue().set(BLOCK_PREFIX + ip, "true");
                stringRedisTemplate.delete(LIMIT_PREFIX + ip);
                throw new ServiceException(ExceptionEnum.UNDER_ATTACK.getCode(), ip+ExceptionEnum.UNDER_ATTACK.getMsg(),true);
            }
        }
        return true;
    }
}
